import {register} from "../../service/auth";
import {baseUrl} from "../../utils/config";
import {doLogin} from "../../utils/doLogin";
const validate = require('../../utils/validate')
// pages/register/register.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    email: '',
    password: '',
    password_confirmation: '',
    error_name: '',
    error_email: '',
    error_password: '',
    error_password_confirmation: '',

    avatar: baseUrl + "/imgs/avatar.png"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  getWxUserInfo() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        this.setData({
          name: res.userInfo.nickName,
          avatar: res.userInfo.avatarUrl
        })
      }
    })
  },

  /**
   * 执行注册
   */
  register() {
    //表单验证
    const check = this.checkInput()
    if (!check) return

    const data = {
      name: this.data.name, //this.data.name
      email: this.data.email,
      password: this.data.password,
      password_confirmation: this.data.password_confirmation,
      avatar: this.data.avatar,
      openid: wx.getStorageSync('openid')
    }
    // const {name, email, password, password_confirmation, avatar} = this.data
    //执行注册
    register(data).then(() => {
      const params = {
        email: this.data.email,
        password: this.data.password
      }
      console.log(params)
      // const params = {email, password}
      //自动登录
      doLogin(params, "register")
    })
  },

  /**
   * 验证用户输入的内容
   * @returns {boolean}
   */

  checkInput() {
    // const {name, email, password, password_confirmation} = this.data

    // const checkName = validate.min(name, 2)
    // const checkEmail = validate.email(email)
    // const checkPassword = validate.min(password, 6)
    // const checkConfirm = validate.confirm(password, password_confirmation)

    const checkName = validate.nickName(this.data.name, 2)
    const checkEmail = validate.email(this.data.email)
    const checkPassword = validate.min(this.data.password, 6)
    const checkPassWordConfirmation = validate.same(this.data.password, this.data.password_confirmation)

    //表单验证
    if (!checkName) {
      this.setData({
        error_name: '昵称最少两个字符'
      })
    } else {
      this.setData({
        error_name: ''
      })
    }
    if (!checkEmail) {
      this.setData({
        error_email: '请输入正确的邮箱格式'
      })
    } else {
      this.setData({
        error_email: ''
      })
    }
    if (!checkPassword) {
      this.setData({
        error_password: '密码最少6位'
      })
    } else {
      this.setData({
        error_password: ''
      })
    }
    if (!checkPassWordConfirmation) {
      this.setData({
        error_password_confirmation: '两次输入的密码不一致'
      })
    } else {
      this.setData({
        error_password_confirmation: ''
      })
    }
    if (checkName && checkEmail && checkPassword && checkPassWordConfirmation) return true
    return false
  }
})